import { CityPickerProps, CityPickerValue } from './interface';

import cityData from './districtDist.json';

// 省原始数据
const PROVINCE: Readonly<CityPickerValue>[] = [];
// 市原始数据
const CITY: Readonly<CityPickerValue>[] = [];
// 区原始数据
const AREA: Readonly<CityPickerValue>[] = [];

for (let i = 0; i < cityData.length; i++) {
  const item: CityPickerValue = {
    label: cityData[i].name,
    value: cityData[i].adcode,
    parentAdcode: String(cityData[i].parentAdcode),
    mergerShortName: cityData[i].mergerShortName.replace(/,|，/g, '-'),
  };
  if (cityData[i].levelInt === 1) {
    PROVINCE.push(Object.freeze(item));
  }
  if (cityData[i].levelInt === 2) {
    CITY.push(Object.freeze(item));
  }
  if (cityData[i].levelInt === 3) {
    AREA.push(Object.freeze(item));
  }
}

// 根据 adcode 获取初始化数据
export function getValueByCode(
  code?: string,
  type?: 'city' | 'province' | 'area',
): CityPickerProps['value'] | undefined {
  if (!code) {
    return;
  }
  if (type === 'area') {
    const area = AREA.find((v) => v.value === code);
    if (area) {
      const city = CITY.find((v) => v.value === area?.parentAdcode);
      if (city) {
        return {
          ...area,
          path: [city.parentAdcode, city.value, area.value],
        };
      }
    }
  } else if (type === 'city') {
    const city = CITY.find((v) => v.value === code);
    if (city) {
      return {
        ...city,
        path: [city.parentAdcode, city.value],
      };
    }
  } else if (type === 'province') {
    const province = PROVINCE.find((v) => v.value === code);
    if (province) {
      return {
        ...province,
        path: [province.value],
      };
    }
  } else {
    return getValueByCode(code, 'area') || getValueByCode(code, 'city') || getValueByCode(code, 'province');
  }
}

export function getOptions() {
  const areas = AREA.map((v) => ({ ...v }));

  const citys = CITY.map((v) => {
    return {
      ...v,
      children: areas.filter((area) => area.parentAdcode === v.value),
    };
  });

  return PROVINCE.map((v) => {
    return {
      ...v,
      children: citys.filter((city) => city.parentAdcode === v.value),
    };
  });
}
